<template>
	<view class="padding_48rpx">

		<view class="myNmae flex-between ">
			<text style="min-width: 150rpx;">优惠券名称</text>
			<input  v-model="form.name" placeholder="请输入优惠券名称" />
		</view>

		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 150rpx;">优惠券类型</text>
			<picker mode="selector" @change='region' :range="regionList" :range-key="'text'">
				<view class="flex">
					<text>{{selsectRegion}}</text>
					<uni-icons type="right" size="15"></uni-icons>
				</view>
			</picker>
		</view>
		<view class="myNmae flex-between margin-top_60rpx" v-if="isShowdiscount">
			<text style="min-width: 150rpx;">满足金额</text>
			<input type="number" v-model="form.trigger_amount" placeholder="请输入满足金额" />
		</view>
		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 150rpx;">优惠金额</text>
			<input type="number" v-model="form.discount_intensity" placeholder="请输入优惠金额" />
		</view>
		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 150rpx;">使用描述</text>
			<input  v-model="form.desc" placeholder="请输入描述" />
		</view>
		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 150rpx;">使用范围</text>
			<picker mode="selector" @change='classifyFn' :range="classifyList" :range-key="'text'">
				<view class="flex">
					<text>{{classify}}</text>
					<uni-icons type="right" size="15"></uni-icons>
				</view>
			</picker>
		</view>
		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 150rpx;">开始时间</text>
			<picker mode="date" :value="date" :fields="currentTimeFn(currentTime)" :start="startDate" :end="endDate"
				@change="bindDateChange">
				<view class="flex-align-center-justify-start  color6">
					<view class="" v-if="yeartime&&monthtime&&daytime">
						{{ yeartime }}
						<text>-</text>
						{{ monthtime }}
						<text>-</text>
						{{ daytime }}
						<uni-icons type="right" color='#333' size="16"></uni-icons>
					</view>
					<view class="" v-else>
						<text>请选择开始时间</text>
						<uni-icons type="right" color='#333' size="16"></uni-icons>
					</view>

				</view>

			</picker>
		</view>
		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 150rpx;">结束时间</text>
			<picker mode="date" :value="date1" :fields="currentTimeFn1(createTime1)" :start="startDate1" :end="endDate1"
				@change="bindDateChange1">
				<view class="flex-align-center-justify-start  color6">
					<view class="" v-if="yeartime1&&monthtime1&&daytime1">
						{{ yeartime1 }}
						<text>-</text>
						{{ monthtime1 }}
						<text>-</text>
						{{ daytime1 }}
						<uni-icons type="right" color='#333' size="16"></uni-icons>
					</view>
					<view class="" v-else>
						<text>请选择结束时间</text>
						<uni-icons type="right" color='#333' size="16"></uni-icons>
					</view>

					<!-- <image class="arrowImg" src="../../static/124.png" mode=""></image> -->

				</view>

			</picker>
		</view>
		<view class="btnSure flex" @click="newAdd()">
			立即添加
		</view>

	</view>
</template>

<script>
	import moment from 'moment';
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		components: {

		},
		data() {
			const currentDate = this.getDate({
				format: true
			});

			return {
				yeartime: '',
				//选择的月份
				monthtime: '',
				//选择的天数
				daytime: '',
				yeartime1: '',
				//选择的月份
				monthtime1: '',
				//选择的天数
				daytime1: '',
				date: null,
				date1: null,
				selsectRegion: '请选择',
				classify: '请选择',
				currentTime: '1',
				createTime1: '1',
				form: {
					// 名称
					name: '',
					// 满足金额
					trigger_amount: '',
					// 优惠金额
					discount_intensity: '',
					// 优惠类型 1 抵扣券 2 新人券 3 赠送券
					type: '',
					// 描述
					desc: '',
					// 分类id
					classify_id: '',
					// 开始时间
					start_time: '',
					// 结束时间
					end_time: ''
				},

				regionList: [{
					text: '抵扣券',
					value: '1'

				}, {
					text: '新人券',
					value: '2'

				},  ],
				allArr: [{
					text: '全部',
					value: '0'
				}],
				token: uni.getStorageSync('login').token,
				classifyList: [],
				isShowdiscount: false,
				
				isEdit:false
			}
		},
		onLoad(options) {
		     this.init()
			if(options.id){
			   this.form.id=''
			    
				this.$sun.assignObject(this.form, {
					...options
				})
				// 测试 
				var targetstart = moment(options.start_time);
				var formattedstart = targetstart.format('YYYY-MM-DD');
				var targetend = moment(options.end_time);
				var formattedend = targetend.format('YYYY-MM-DD');
				this.form.start_time=formattedstart
				this.form.end_time=formattedend
				// 开始时间
				this.yeartime = this.form.start_time.split('-')[0];
				this.monthtime = this.form.start_time.split('-')[1];
				this.daytime = this.form.start_time.split('-')[2];
				
				// 结束时间
				this.yeartime1 = this.form.end_time.split('-')[0];
				this.monthtime1 = this.form.end_time.split('-')[1];
				this.daytime1 = this.form.end_time.split('-')[2];
			   // 编辑 优惠卷类型
			   const couponType=this.regionList.find((item)=>{
				   return item.value== this.form.type
			   })
			
				this.selsectRegion=couponType.text
				if(this.selsectRegion!='无门槛券'){
					this.isShowdiscount=true
				}
				this.isEdit=true
				
				
				console.log(this.form)
			}
			
		},
		onShow() {

			this.$at.releaseKey('submit');
		},
		methods: {
			async init() {
				// 查询分类列表
				const result = await this.$http.post({
					url: this.$api.classifyList,
					data: {


					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				if (result.code == 0) {
					const classifyData = result.data.list.map((item) => {
						return {
							text: item.name,
							value: item.id
						}
					})
					this.classifyList = [...this.allArr, ...classifyData]
					
					if(this.isEdit){
						const classifyType= this.classifyList.find((item)=>{
					
							return item.value==this.form.classify_id
						})
						console.log(classifyType)
						this.classify=classifyType.text
					}

				} else {
					this.$sun.toast(result.msg, 'none')
				}
			},
			newAdd() {

				this.$at.uniDoFunc({
					key: 'submit',
					success: async () => {
						this.$at.lockKey('submit');
						// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择
						if (!this.form.name) {
							this.$sun.toast("请填写优惠券名称", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.type) {
							this.$sun.toast("请选择优惠券类型", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.discount_intensity) {
							this.$sun.toast("请填写优惠金额", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.trigger_amount && this.isShowdiscount) {
							this.$sun.toast("请填写满足金额", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.desc) {
							this.$sun.toast("请填写描述", 'none')
							this.$at.releaseKey('submit');
						} else if (this.form.classify_id === '') {
							this.$sun.toast("请选择范围", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.start_time && !this.form.end_time) {
							this.$sun.toast("请填写开始结束时间", 'none')
							this.$at.releaseKey('submit');
						} else {
							console.log(this.form)
						
							const saveOrUpdate = this.isEdit ? this.$api.editCoupon :this.$api.addCoupon;
							const result = await this.$http.post({
								url: saveOrUpdate,
								data: {
									...this.form

								},
								headers: {
									'Authorization': `Bearer ${this.token}`
								}

							})
							if (result.code == 0) {
								
                               this.$sun.toast(result.msg, 'none')
						       setTimeout(()=>{
								   this.$sun.navBack()
							   },500)
							  
							} else {
								this.$sun.toast(result.msg, 'none')
							}

							this.$at.releaseKey('submit');
						}
					}
				});


			},
			region(e) {
				console.log(e)
				if (this.regionList[e.detail.value].text != '无门槛券') {
					this.isShowdiscount = true
				} else {
					this.isShowdiscount = false
				}

				this.selsectRegion = this.regionList[e.detail.value].text
				this.form.type = this.regionList[e.detail.value].value


			},
			classifyFn(e) {

				this.form.classify_id = this.classifyList[e.detail.value].value
				console.log(this.form.classify_id)
				this.classify = this.classifyList[e.detail.value].text
			},
			// 日期获取
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;

				return `${year}-${month}-${day}`;

			},

			bindDateChange(e) {


				this.createTime = e.detail.value
				this.form.start_time = e.detail.value
				this.date = e.target.value;
				/* 在上面声明变量，split是用来截取字段*/
				this.yeartime = this.date.split('-')[0];
				this.monthtime = this.date.split('-')[1];
				this.daytime = this.date.split('-')[2];


			},
			bindDateChange1(e) {

				console.log(e)
				this.createTime1 = e.detail.value
				this.form.end_time = e.detail.value
				this.date1 = e.target.value;
				/* 在上面声明变量，split是用来截取字段*/
				this.yeartime1 = this.date1.split('-')[0];
				this.monthtime1 = this.date1.split('-')[1];
				this.daytime1 = this.date1.split('-')[2];


			},

		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			},
			startDate1() {
				return this.getDate('start');
			},
			endDate1() {
				return this.getDate('end');
			},
			currentTimeFn() {
				return function(currentIndex) {
					if (currentIndex == '1') {
						// 日
						return 'day';

					} else if (currentIndex == '2') {
						// 月
						return 'month';
					} else if (currentIndex == '3') {
						// 年
						return 'year';
					}
				};
			},
			currentTimeFn1() {
				return function(currentIndex) {
					if (currentIndex == '1') {
						// 日
						return 'day';

					} else if (currentIndex == '2') {
						// 月
						return 'month';
					} else if (currentIndex == '3') {
						// 年
						return 'year';
					}
				};
			}




		},
	}
</script>

<style lang="less" scoped>
	.edit {

		height: 54px;
		background: rgb(246, 248, 255);



	}

	.myNmae {

		background-color: #fff;
		min-width: 50rpx;

		.avatar {
			width: 84rpx;
			height: 84rpx;
		}

		input {
			text-align: right;
		}

		.backgroundImg {

			height: 154rpx;


		}

	}

	.btnSure {
		width: 655rpx;
		height: 76rpx;
		background: rgb(81, 142, 247);
		color: rgb(255, 255, 255);
		border-radius: 108rpx;
		font-size: 32rpx;
		font-weight: 700;
		position: fixed;
		bottom: 20rpx;
	}

	page {
		background: #fff;
	}
</style>